package com.goliathonline.android.kegbot;

import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;

import org.json.JSONArray;
import org.json.JSONObject;

public class Kegbot extends TabActivity {
	private String _host;
	private int _port;
	private SharedPreferences _prefs;
	private NotificationManager mNotificationManager;
	private int notifCounter;
	private Util _util = new Util();
	private static final String FLOW_UPDATE = "com.goliathonline.android.kegbot.flow_update";
	private Background _kegnetListener;
	private IntentFilter _filter;
	private KegnetReceiver _r;
	private TabHost _mTabHost;
	private ArrayAdapter<String> _bb;
	private ListView _drinksListView;
	
	

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setupTabs();			// Setup Tabs
        getPrefs();				// Load Settings
        UpdateDrinks();
        SetupKegnetReceiver();
        StartKegnetListener();
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notifCounter = 2;
        //SetBackgroundIcon();	// Turn on background Icon
        						// Start background listening service
        						// Load current status (Keg,Tap info)
        						// BE SURE TO ERROR CHECK CONNECTION FOR ALL THE ABOVE
    }
    
    private void setupTabs()
    {
    	_mTabHost = getTabHost();
        ListView statusListView = (ListView)findViewById(R.id.statuslistview);
        _drinksListView = (ListView)findViewById(R.id.drinkslistview);
        ListView adminListView = (ListView)findViewById(R.id.adminlistview);
           
        final ArrayList<String> statusItems = new ArrayList<String>();
        statusItems.add("Token");
        statusItems.add("Flow meter");
        final ArrayAdapter<String> aa;
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, statusItems);
        statusListView.setAdapter(aa);
        
        final ArrayList<String> drinksItems = new ArrayList<String>();
        drinksItems.add("a drink");
        _bb = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, drinksItems);
        _drinksListView.setAdapter(_bb);
        
        final ArrayList<String> adminItems = new ArrayList<String>();
        adminItems.add("Taps");
        adminItems.add("Users");
        adminItems.add("Tokens");
        adminItems.add("Pictures");
        final ArrayAdapter<String> cc;
        cc = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, adminItems);
        adminListView.setAdapter(cc);

        _mTabHost.addTab(_mTabHost.newTabSpec("tab_test1").setIndicator("Status").setContent(R.id.statuslistview));
        _mTabHost.addTab(_mTabHost.newTabSpec("tab_test2").setIndicator("Drinks").setContent(R.id.drinkslistview));
        _mTabHost.addTab(_mTabHost.newTabSpec("tab_test3").setIndicator("Admin").setContent(R.id.adminlistview));
        _mTabHost.setCurrentTab(0);
    }
    
    private void UpdateDrinks()
    {	
		API api = new API();
    	api.SetHost(_host, 81);
    	JSONObject json;
    	try {
    		json = new JSONObject(api.GetLast10());
			JSONArray jsonarray = json.optJSONArray("result");
			JSONObject element;
			String drink;
			Double oz;
			DecimalFormat df = new DecimalFormat("###.##");
			_bb.clear();
			for (int i = 0; i < jsonarray.length(); i++)
			{
				element = jsonarray.getJSONObject(i);
				drink = (String)element.get("user_id");
				oz = _util.MillToOz(element.getDouble("volume_ml"));
				drink = drink + ": " + df.format(oz) + "oz";
				_bb.add(drink);
			}
		} catch (Exception e) {
			Log.d("Kegbot JSON",e.toString());
		}
    	
    	_drinksListView.setAdapter(_bb);
    }
    
    private void getPrefs()
	{
		//Get the xml/preferences.xml preferences
		_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		_host = _prefs.getString("hostPref", "kegbot");
		_port = Integer.parseInt(_prefs.getString("port", "9805"));
		if (_host == "kegbot")
		{
			Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
    		startActivity(settingsActivity);
		}
	}
    
    private void SetupKegnetReceiver()
    {
    	// Create and register the broadcast receiver.
    	_filter = new IntentFilter(FLOW_UPDATE);
    	_r = new KegnetReceiver();
    	registerReceiver(_r, _filter);
    	Log.d("Kegbot","Setup Kegnet Receiver");
    }
    
    private void StartKegnetListener()
    {
    	_kegnetListener = new Background();
    	Intent service = new Intent();
    	service.setClassName("com.goliathonline.android.kegbot",Background.class.getName());
    	startService(service);
    	Log.d("Kegbot","Started Kegnet Listener");
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = new MenuInflater(this);
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	getPrefs();
    	 switch (item.getItemId()) {
    	    case R.id.setup:
        		Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
        		startActivity(settingsActivity);
    	        return true;
    	    case R.id.about:
    	    	DisplayDialog("About","This application was created by Jared Szechy.");
    	    	//_util.JsonToProto(_util.StringToJson(_conn.Listen()));
    	    	return true;
    	    case R.id.exit:
    	    	System.exit(0);
    	    	return true;
    	    default:
    	    	DisplayDialog("Debug", "Button id: " + item.getItemId());
    	        return true;
    	    }
    }
    public void DisplayDialog(String title, String message)
    {
    	AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    	dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);
		dialogBuilder.setCancelable(true);
		dialogBuilder.create().show();
    }
    
    public void SendTestNotify()
	{
		//Notification Test
    	int icon = R.drawable.keg;        				// icon from resources
    	CharSequence tickerText = "New Drink";             // ticker-text
    	long when = System.currentTimeMillis()+10000;         // notification time
    	Context context = getApplicationContext();      // application Context
    	CharSequence contentTitle = "New Drink Poured";  	// expanded message title
    	CharSequence contentText = "User poured 13oz of beer.";      // expanded message text

    	Intent notificationIntent = new Intent(this, Kegbot.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	// the next two lines initialize the Notification, using the configurations above
    	Notification notification = new Notification(icon, tickerText, when);
    	notification.flags |= Notification.DEFAULT_SOUND;
		notification.flags |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	
		mNotificationManager.notify(notifCounter, notification);
		notifCounter++;
	}
    
    public void SetBackgroundIcon()
	{
    	int icon = R.drawable.keg;        				// icon from resources
    	CharSequence tickerText = "Kegbot";             // ticker-text
    	long when = System.currentTimeMillis();         // notification time
    	Context context = getApplicationContext();      // application Context
    	CharSequence contentTitle = "Kegbot Running";  	// expanded message title
    	CharSequence contentText = "The Kegbot application is running.";      // expanded message text

    	Intent notificationIntent = new Intent(this, Kegbot.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	// the next two lines initialize the Notification, using the configurations above
    	Notification notification = new Notification(icon, tickerText, when);
    	notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.flags |= Notification.FLAG_NO_CLEAR;
    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	
    	final int NOTIF_ID = 1;
		mNotificationManager.notify(NOTIF_ID, notification);
	}
    
    @Override
    protected void onStop(){
    	mNotificationManager.cancel(1);
    	unregisterReceiver(_r);
    	super.onStop();
    
    }
}